package com.zenithmind.common.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT令牌中继过滤器
 * 用于微服务间传递JWT令牌，确保用户身份在微服务调用链中保持一致
 */
@Slf4j
@Component
public class TokenRelayFilter extends OncePerRequestFilter {

    private static final String AUTHORIZATION_HEADER = "Authorization";
    private static final String BEARER_PREFIX = "Bearer ";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) 
            throws ServletException, IOException {
        
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        
        if (authentication instanceof JwtAuthenticationToken) {
            JwtAuthenticationToken jwtAuthentication = (JwtAuthenticationToken) authentication;
            String tokenValue = jwtAuthentication.getToken().getTokenValue();
            
            log.debug("Relaying token to outgoing request: {}", maskToken(tokenValue));
            
            // 在当前请求中添加令牌，用于后续的Feign或RestTemplate调用
            request.setAttribute("zenithmind.jwt.token", tokenValue);
        }
        
        filterChain.doFilter(request, response);
    }
    
    /**
     * 遮蔽令牌，仅显示前10个和后5个字符
     */
    private String maskToken(String token) {
        if (token == null || token.length() < 20) {
            return "***masked***";
        }
        return token.substring(0, 10) + "..." + token.substring(token.length() - 5);
    }
} 